package com.haixiaoke.saas.repository.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.haixiaoke.saas.repository.mapper.OrderContractMapper;
import com.haixiaoke.saas.repository.pojo.BacklogItem;
import com.haixiaoke.saas.repository.pojo.HousingAllocation;
import com.haixiaoke.saas.repository.pojo.Order;
import com.haixiaoke.saas.repository.pojo.OrderContract;
import com.haixiaoke.saas.repository.service.IBacklogItemService;
import com.haixiaoke.saas.repository.service.IOrderContractService;
import com.haixiaoke.saas.repository.service.IOrderService;
import com.haixiaoke.saas.repository.util.GsonUtil;
import com.mzj.saas.commons.enums.BacklogItemTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单合同Service业务层处理
 *
 * @author zhiping
 * @date 2023-04-20
 */
@Service
public class OrderContractServiceImpl implements IOrderContractService {


    /**
     * 合同已签
     */
    private final Integer ORDER_CONTRACT_SIGNED = 1;

    /**
     * 合同未签
     */
    private final Integer ORDER_CONTRACT_UNSIGNED = 2;

    @Autowired
    private OrderContractMapper orderContractMapper;
    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private IBacklogItemService iBacklogItemService;

    /**
     * 查询订单合同
     *
     * @param contractId 订单合同主键
     * @return 订单合同
     */
    @Override
    public OrderContract selectOrderContractByContractId(Long contractId) {
        return orderContractMapper.selectOrderContractByContractId(contractId);
    }

    /**
     * 查询订单合同列表
     *
     * @param orderContract 订单合同
     * @return 订单合同
     */
    @Override
    public List<OrderContract> selectOrderContractList(OrderContract orderContract) {
        return orderContractMapper.selectOrderContractList(orderContract);
    }

    /**
     * 新增订单合同
     *
     * @param orderContract 订单合同
     * @return 结果
     */
    @Override
    public int insertOrderContract(OrderContract orderContract) {
        orderContract.setGenerateTime(DateUtil.date());
        return orderContractMapper.insertOrderContract(orderContract);
    }

    /**
     * 修改订单合同
     *
     * @param orderContract 订单合同
     * @return 结果
     */
    @Override
    public int updateOrderContract(OrderContract orderContract) {
        orderContract.setStatus(ORDER_CONTRACT_SIGNED);
        orderContract.setSignTime(DateUtil.date());
        return orderContractMapper.updateOrderContract(orderContract);
    }

    /**
     * 批量删除订单合同
     *
     * @param contractIds 需要删除的订单合同主键
     * @return 结果
     */
    @Override
    public int deleteOrderContractByContractIds(Long[] contractIds) {
        return orderContractMapper.deleteOrderContractByContractIds(contractIds);
    }

    /**
     * 删除订单合同信息
     *
     * @param contractId 订单合同主键
     * @return 结果
     */
    @Override
    public int deleteOrderContractByContractId(Long contractId) {
        return orderContractMapper.deleteOrderContractByContractId(contractId);
    }

    @Override
    public List<OrderContract> selectOrderContractByOrderId(String orderId) {
        return orderContractMapper.selectOrderContractByOrderId(orderId);
    }

    @Override
    public List<OrderContract> selectOrderContractByOrderIdAndStatus(String orderId, Integer contractStatus) {
        return orderContractMapper.selectOrderContractByOrderIdAndStatus(orderId, contractStatus);
    }

    @Override
    public void orderContractDeadlineTask() {
        List<OrderContract> orderContracts = orderContractMapper.selectOrderContractByCheckOutTime();
        List<String> orderIds = orderContracts.stream().map(OrderContract::getOrderId).distinct().collect(Collectors.toList());
        String[] orderIdsStr = orderIds.toArray(new String[orderIds.size()]);
        List<Order> orders = iOrderService.selectOrderByIds(orderIdsStr);
        Map<String, Order> orderMap = orders.stream().collect(Collectors.toMap(Order::getOrderId, order -> order));
        DateTime nowTime = DateUtil.date();
        List<BacklogItem> backlogItems = new ArrayList<>();
        for (OrderContract orderContract : orderContracts) {
            Date checkOutTime = orderContract.getCheckOutTime();
            //当前时间在退房时间之前，则处理代办事项
            if (nowTime.before(checkOutTime)) {
                boolean result = false;
                Order order = orderMap.get(orderContract.getOrderId());
                //订单为已验房才创建待办事项
                if (Order.ORDER_STATE_INSPECTION.equals(order.getOrderState())) {
                    HousingAllocation housingAllocation = GsonUtil.toBean(order.getAllocationContent(), HousingAllocation.class);
                    if (HousingAllocation.APARTMENT_TYPE_SHORT.equals(housingAllocation.getApartmentType())) {
                        long day = DateUtil.betweenDay(nowTime, checkOutTime, false);
                        if (day == 3) {
                            result = true;
                        }
                    } else if (HousingAllocation.APARTMENT_TYPE_LONG.equals(housingAllocation.getApartmentType())) {
                        long month = DateUtil.betweenMonth(nowTime, checkOutTime, false);
                        if (month ==1){
                            result = true;
                        }
                    }
                    if (result) {
                        //创建合约到期的待办事项
                        BacklogItem backlogItem = new BacklogItem();
                        //房屋id
                        backlogItem.setHouseId(order.getHouseId());
                        // 如果是公租房取产权单位id，如果是非公租房取物业公司id
                        backlogItem.setOrgId(order.getOrgId());
                        //个人组织id
                        backlogItem.setUserOrgId(order.getOrgId());
                        //待办事项类型
                        backlogItem.setType(BacklogItemTypeEnum.APARTMENT_CONTRACT.getValue());
                        //标题
                        backlogItem.setTitle("租约提醒");
                        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
                        String checkOutTimeStr = format.format(checkOutTime);
                        //内容
                        backlogItem.setContent(order.getResidenceCommunityName()+"小区"+order.getBuildingNumName()+"栋"+order.getUnitName()+"单元"+order.getRoomNumber()+"房，您的租约将于"+checkOutTimeStr+"到期，请尽快办理续租或退租业务，以免影响您的居住体验。");
                        backlogItem.setBusinessStatus("待查看");
                        backlogItem.setHandleStatus(0);
                        backlogItem.setMatchUserId(order.getReservationId());
                        backlogItem.setPhone(order.getReservationPhone());
                        //操作人id
                        backlogItem.setOperatorId(order.getReservationId());
                        //操作时间
                        backlogItem.setCreateTime(nowTime);
                        backlogItems.add(backlogItem);
                    }
                }
            }
        }
        if (backlogItems.size()>0) {
            iBacklogItemService.insertBacklogItems(backlogItems);
        }
    }
}
